package com.wish.g01.system.controller;

import cn.hutool.core.util.RandomUtil;
import com.wish.g01.common.core.domain.R;
import com.wish.g01.common.core.web.domain.AjaxResult;
import com.wish.g01.common.redis.service.RedisService;
import com.wish.g01.system.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/sms")
@Slf4j
public class SmsController {

    @Autowired
    RedisService redisService;

    @Autowired
    private SmsService smsService;

    @GetMapping("/send")
    public R sendCode(String telephone){
        //首先判断手机号是否为空
        if (null==telephone){
            return R.fail("手机号不能为空");
        }
        //判断手机号是否符合格式
      /*  if (!RegexValidateUtil.checkphone(telephone)){
            return Result.setResult(ResponseEnum.MOBILE_ERROR);
        }*/
        //随机生成一个四位数字的验证码
        String code = RandomUtil.randomNumbers(4);
        System.out.println("验证码为："+code);
        //然后调用业务方法发送短信
        boolean b = smsService.sendShortMessage(telephone,code);
        //判断短信是否发送成功，（true为成功，false为失败）
        if (b){
            //发送成功，将验证存入到redis缓存中，并设置有效期
//            String key = "ymjr:sms:code:"+code;
//            redisService.setCacheObject(key,code,120L,TimeUnit.SECONDS);
            return R.ok(code);
        }
        return R.fail("短信发送失败");

    }

}
